package com.phy.kim.foroffer;

/**
 * @author RiceDoggyRoll
 */
public class Offer002AddBinary {

  public String addBinary(String a, String b) {
    StringBuilder ans = new StringBuilder();
    char[] charsA = a.toCharArray();
    char[] charsB = b.toCharArray();
    int carrier = 0;
    int ar = charsA.length - 1, br = charsB.length - 1;
    while (ar >= 0 || br >= 0) {
      int tempA = ar >= 0 ? charsA[ar] - '0' : 0;
      int tempB = br >= 0 ? charsB[br] - '0' : 0;
      int sum = tempA + tempB + carrier;
      carrier = sum >= 2 ? 1 : 0;
      sum = sum >= 2 ? sum - 2 : sum;
      ans.append(sum);
      ar--;
      br--;
    }
    if (carrier == 1) {
      ans.append(1);
    }
    return ans.reverse().toString();
  }
}
